
import java.io.*;
import java.net.*;

// application mimics what the code on the arduino board should do

public class BatMonSpewer {

	static Socket client = null;
	static String serverAddr = "localhost";
	static int serverPort = 8888;
	static DataOutputStream out;
	static boolean connected = false;
	
	
	
	//fields in the packet sent to the server:
	static int id = 0;
	static String ipaddress = "0.0.0.0";
	static int valADC = 0;
	static double valVMonPin = 0.00;
	static double valVMonBat = 00.00;

	public static void main(String[] args) {
		new BatMonSpewer();
		
		connect();
		
		
		while (connected) {
			
			try {
				
				//read & calculate values
				valADC = 1023;
				valVMonPin = 5.00;
				valVMonBat = 24.008;
				
				
				//format the string
				String s = String.format("%03d", id) + 
					"|" + ipaddress + 
					"|" + String.format("%04d",valADC) +
					"|" + String.format("%.3g", valVMonPin) + 
					"|" + String.format("%.4g", valVMonBat) + 
					"\n";
				
				//send the string
			
				send(s);
				
				//Sleep for 1 sec
				Thread.sleep(1000);
				
			} catch (Exception e) {
				e.printStackTrace();
				disconnect();
			}
			
		}

	}
	
	public BatMonSpewer() {
		//generate a random ID (for test purposes only)
		int minID = 1;
		int maxID = 999;
		id = minID + (int)(Math.random() * ((maxID - minID) + 1));
		

	}
	
	public static void connect() {
        try {
			client = new Socket(serverAddr, serverPort);
	        System.out.println("Client: " + client);
	        ipaddress = client.getLocalAddress().toString().substring(1);
	        connected = true;
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void disconnect() {
        try {
        	connected = false;
        	out.close();
			client.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void send(String s) throws IOException {
		try {
			out = new DataOutputStream(client.getOutputStream());
			out.writeBytes(s);
			out.flush();
		} catch (IOException e) {
			throw e;
		}
	}
	
	public static void quit() {
		disconnect();
		System.exit(0);  
	}

}
